from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QMessageBox
from PyQt5.QtGui import *
from TDC import *
from cursorsetting import *
from Expsetting import *
from PyQt5.Qt import *
from pyqtgraph import PlotWidget
from PyQt5 import QtCore
from numba import jit
import csv
import numpy as np
import pyqtgraph as pq
import datetime
import matplotlib
import matplotlib.pyplot as plt
import time
import os
import shutil
from collections import Counter
try:
        import QuTAG
except:
        print("Time Tagger wrapper QuTAG.py is not in the search path.")
qutag = QuTAG.QuTAG()
data = qutag.getLastTimestamps(True)
time.sleep(0.5)
data = qutag.getLastTimestamps(True)
#print(data[0])
path = r'C:\Users\InQlab_QEN\Desktop\quTAG_TDC_python\DataRecording\50uw'
# pathtrue=os.path.exists(path)
# if pathtrue:
#         shutil.rmtree(path)
#         os.mkdir(path)
# else:
#         os.mkdir(path)
filename = path+'\DataRecording' + '.CSV'
data=np.array(data)
d=data.T

print(str(d[0]))
with open(filename,'a') as f_handle:
    np.savetxt(f_handle,d, delimiter = ',')
# f = open(filename, 'w')
# data=np.array(data)
# d=data.T
# #d=d.tolist()
# print(data)
# #f.write(str(d[0]))
# np.savetxt(filename, d, delimiter = ',')
# starttime=datetime.datetime.now()
# print('start: ',datetime.datetime.now())
# @jit
# def cal(data1,data2):
#     count2 = 0
#     channeltime1 = []
#     channeltime2 = []
#     sweeps = 0
#   #  time = 0
#     det1 = 0
#     det2 = 0
#     count1 = 0
#     count2 = 0
#     coin12 = 0
#     print(len(data1))
#     for i in np.arange(0,len(data1),1):
#         if data2[i] == 2:
#             if det1 != 0 and det2 != 0:
#                 coin12 = coin12 + 1
#                 sweeps = sweeps + 1
#                 det1 = 0
#                 det2 = 0
#             else:
#                 sweeps = sweeps + 1
#                 det1 = 0
#                 det2 = 0
#         elif data2[i] == 1:# and 558500 < data1[i] < 559500:  # jiacursor
#             channeltime1.append(data1[i] / 1000)
#             det1 = det1 + 1
#             count1 = count1 + 1
#         elif data2[i] == 3: #and 295000 < data1[i] < 297000:
#             channeltime2.append(data1[i] / 1000)
#             det2 = det2 + 1
#             count2 = count2 + 1
#         else:
#             a = 0
#
#     return [count1,count2,coin12,sweeps]
# data = qutag.getLastTimestamps(True)
# time.sleep(1)
# for i in np.arange(1,2,1):
#     data = qutag.getLastTimestamps(True)
#     data=np.array(data)
#     data00 = np.trunc(data[0]/100)*100
#     print(data00)
#     data11 = data[1]
#     print(data11)
#     result=cal(data00,data11)
#     print('time,',datetime.datetime.now())
#     print(result)
# # print(type(data0))
# # print(len(data1))
# # print("Timestamps in an array:")
# # print(data0[1])
# print('start:',starttime)
# print('stop: ',datetime.datetime.now())